<template>
  <div
   :class="['t-multilingual']"
    v-show="mappingProps.visible"
    tabIndex='-1'
  >
  <LabelPrefixWraper

    v-bind="mappingProps"
    tabindex="-1"
  >
  </LabelPrefixWraper>
    <!-- {{ inputDom.find(item =>item.classList.includes('MultilingualText_'+i.langSuffix) ) }} -->
    <div ref="ref_mutilingual_parent" style="width: 100%"     :class="['t-multilingual']"
>
      <t-input
        :autoResizeEnabled="mappingProps.resize"
        :placeholder="mappingProps.placeholder"
        :isMaster="i.IsMaster"
        borderless
         @focus="focus"
        :ref="'ref_language_' + i.langSuffix"
        :style="
          index != mappingProps.localInfoList.length - 1
            ? 'margin-bottom:' + mappingProps.space + 'px'
            : 'margin-bottom:0px'
        "
        inputStyle="height:auto"
        v-for="(i, index) in getLangList()"
        :key="i.lang"
        v-model="response[i.langSuffix]"
        :rules="
          mappingProps.requiredMultRule == 'Master'
            ? i.IsMain
              ? mappingProps.maxLength ?  mainRules : mappingProps.rules
              : []
            :  i.IsMain && mappingProps.maxLength ?  mainRules : mappingProps.rules
        "
      >
        <template v-slot:default>
          <div
            :class="
              (() => {
                return `MultilingualText_Parent MultilingualText_${i.langSuffix}`;
              })()
            "
            style="width: 100%"
          >
          </div>
        </template>
      </t-input>
    </div>

    <div ref="ref_mutilingual" style="display: none"> </div>
  </div>
</template>

<script>
/**
 * @数据源
 * @标题
 * @placeholder
 * @hintmode
 * @defaultvalue
 * @readlony
 * @visible
 * @Space 输入框间距
 * @isTextArea 是否单行文本
 *
 */
import useMappingProps from 't/common/hooks/useMappingProps';
import { fixNameSpace } from 't/common/utils';
import { defineComponent, onMounted, ref, watch,computed } from 'vue';
import LabelPrefixWraper from '../../basic/label-prefix-wraper';
// import Multilingual from './Multilingual.vue';
import TInput from 't/basic/input';
import { MultilingualComponent } from './customElements.js';
import './index.scss';
export default defineComponent({
  name: fixNameSpace('multilingual'),
  components: { LabelPrefixWraper, TInput },
  props: {
    // ...commonProps,
    ...LabelPrefixWraper.props,
    placeholder: String, //占位内容
    showHint: Boolean, //悬停文字
    hintMode: String, //文字内容(自定义、同位内容)
    hintMsg: String, //自定义文字
    defaultValue: String, //默认值
    readonly: {
      type: Boolean,
      default() {
        return false;
      },
    },
    value: {
      type: Object,
      default() {
        return {};
      },
    },
    required: {
      type: Boolean,
      default() {
        return false;
      },
    },
    requiredMessage: {
      type: String,
      default() {
        return '';
      },
    },
    requiredMultRule: {
      type: String,
      default() {
        return 'Master';
      },
    },
    maxLength: {
      type: Number,
      default() {
        return 0;
      },
    },
    maxLengthMsg: {
      type: String,
      default() {
        return '';
      },
    },
    localInfoList: {
      type: Array,
      default() {
        return [
          { lang: 'zh_CN', ShortName: '简', langSuffix: '_zh_CN' },
          { lang: 'zh_TW', ShortName: '繁', langSuffix: '_zh_TW' },
          { lang: 'en_US', ShortName: 'EN', langSuffix: '_en_US' },
          { lang: 'jp', ShortName: 'JP', langSuffix: '_jp' },
          { lang: 'fr', ShortName: 'FR', langSuffix: '_fr' },
        ];
      },
    },
    visible: {
      type: Boolean,
      default() {
        return true;
      },
    },
    space: {
      type: String,
      default() {
        return '12';
      },
    },
    isTextArea: {
      type: Boolean,
      default() {
        return true;
      },
    },
    heightAuto: {
      type: Boolean,
      default() {
        return true;
      },
    },
    resize: {
      type: Boolean,
      default() {
        return true;
      },
    },
    rows: String,
    rules: {
      type: Array,
      default: [],
    },
    labelPosition:{
      type: String,
      default() {
        return 'top';
      },
    },
    dataField: {
      type: String,
      default() {
        return '';
      },
    },
  },
  emits: ['update:value', 'change','focus'],
  setup(props, { attrs, emit, expose, slots }) {
    const [mappingProps, mappingExpose] = useMappingProps(props);
    const mainRules = computed(
      () => mappingProps.rules.concat([e => !e||(e.length < mappingProps.maxLength+1) || mappingProps.maxLengthMsg.replace('${value}',mappingProps.maxLength) || Funcs.GetTerms(
              'Schema.Controls.fasr_editor.Terms.characterIsExceeded',
              `超出字符限制，最大允许${mappingProps.maxLength}字符`,
          )])
    );
    const ref_mutilingual = ref(null);
    const ref_mutilingual_parent = ref(null);
    const multilingualInstance = ref(null);
    const language = ref('');
    if (!window.TFF) {
      language.value =
        TFF.common.storage.Cookie.read('teld_locale') ||
        TFF.common.storage.Cookie.read('wrp_systemLocale') ||
        'zh_CN';
    } else {
      language.value = 'zh_CN';
    }
    const getLangList = () => {
      let langList = mappingProps.localInfoList
      let langCode = TFF.common.storage.Cookie.read('teld_locale') ||
        TFF.common.storage.Cookie.read('wrp_systemLocale') ||
        'zh_CN';
      langCode = langCode.replace(/-/, '_');

      // let defaultLang = langList
      //   ? langList.find(item => item.lang == langCode)
      //   : null;

      let defaultLang = langList
        ? langList.find(item => item.IsMain )
        : null;
      if (!defaultLang && langList) {
        defaultLang = langList[0];
      }
      if (!defaultLang) {
        defaultLang = {
          lang: 'zh_CN',
          ShortName: '简',
          langSuffix: '',
        };
      }
      defaultLang.IsMain = true;
      langList = langList
        ? langList.filter(item => item.lang != defaultLang.lang)
        : [];
      langList.map(item => {
        item.IsMain = false;
        return item;
      })
      langList.unshift(defaultLang);
      return langList;
      // return [
      //   { lang: 'zh_CN', ShortName: '简', langSuffix: '' },
      //   { lang: 'zh_TW', ShortName: '繁', langSuffix: '_zh_TW' },
      //   { lang: 'en_US', ShortName: 'EN', langSuffix: '_en_US' },
      //   { lang: 'jp', ShortName: 'JP', langSuffix: '_jp' },
      //   { lang: 'fr', ShortName: 'FR', langSuffix: '_fr' },
      // ];
      //todo 修改成走接口
    };
    const obj = {};
    if (mappingProps.localInfoList) {
      mappingProps.localInfoList.forEach(item => {
        obj['ref_language_' + item.langSuffix] = ref(null);
      });
    }
    const hintPlaceholder = () => {
      const msg = ref('');
      if (mappingProps.showHint) {
        if (mappingProps.hintMode == 'custom') {
          msg.value = mappingProps.hintMsg;
        } else {
          msg.value = mappingProps.placeholder;
        }
      }
      return msg;
    }; //悬停文字相关
        function focus() {
      emit('focus');
    }

    const lang = ref(language);

    const dataValue = ref('');
    const ChangeLang = data => {
      lang.value = data;
    };
    const response = ref({});
    const dataChange = data => {
      if (!response.value[lang.value]) {
        response.value[lang.value] = '';
      }
      response.value[lang.value] = data;
       let langList = multilingualInstance.value.languageInfo;
        langList.forEach(Lang => {
          if (Lang.IsMain) {
             response.value[''] = response.value[Lang.langSuffix];
          }
        })
    };

    const setValue = (varData, val) => {
      //可以支持传入Object
      if (varData instanceof Object) {
        let langList = getLangList();
        for (let i in langList) {
            var langSuffix = langList[i].langSuffix;
            debugger
            let val = varData[mappingProps.dataField + langSuffix];
            if(langList[i].IsMain) {
              val = varData[mappingProps.dataField];
            }
            multilingualInstance.value.setValue(langSuffix, val);
            response.value[langSuffix] = val;

        }

        // for (let key in result) {
        //   let suffix = key;
        //   if (!getLangList()) {
        //     continue;
        //   }
        //   if (getLangList().findIndex(item => item.langSuffix == key) == -1) {
        //     continue;
        //   }

        //   setValue(key, langSuffix[key]);
        // }
        // return;

      }
      // if (
      //   getLangList().findIndex(item => item.langSuffix == langSuffix) == -1
      // ) {
      //   return;
      // }
      // multilingualInstance.value.setValue(langSuffix, val);
    };
    watch(
      () => response.value,
      () => {
        emit('update:value', response.value);
        emit('change', response.value);
      },
      { deep: true },
    );
    watch(
      () => mappingProps.value,
      () => {
        response.value = mappingProps.value;
      },
      { deep: true, immediate: true },
    );
    const validate = lang => {
      debugger;
      let langList = multilingualInstance.value.languageInfo;
      let checkInfo = {};
      let bindPath = '';
      langList.forEach(Lang => {
        if (lang) {
          if (Lang.langSuffix != lang) {
            return;
          }
        }
        let langSuffix = Lang.langSuffix;
        let val = response.value[langSuffix];
        let errmessage = '';
        if (mappingProps.required && !val) {
          if (mappingProps.requiredMultRule == 'Master' && Lang.IsMain) {
            checkInfo[langSuffix] = {
              isMain: Lang.IsMain,
              label: langSuffix,
              message: mappingProps.requiredMessage,
            };
          } else if (mappingProps.requiredMultRule != 'Master') {
            checkInfo[langSuffix] = {
              isMain: Lang.IsMain,
              label: langSuffix,
              message: mappingProps.requiredMessage,
            };
          }
        }
        if (
          mappingProps.maxLength &&
          val &&
          val.length > mappingProps.maxLength
        ) {
          checkInfo[langSuffix] = {
            isMain: Lang.IsMain,
            label: langSuffix,
            message: mappingProps.maxLengthMsg.replace(
              /\${value}/gi,
              mappingProps.maxLength,
            ),
          };
        }
      });
      if (Object.keys(checkInfo).length == 0) {
        return true;
      } else {
        return checkInfo[lang] ? checkInfo[lang].message : '验证失败';
      }
    };
    expose({
      ...mappingExpose,
      setValue,
      modelValue: response.value,
      validate: () => {
        let res = true;
        for (let i in obj) {
          // if (res) {
          if (!obj[i].value[0].validate()) {
                res = false;
              };
          // }
        }
        return res;
      },
    });

    onMounted(() => {
      multilingualInstance.value = new MultilingualComponent(
        ref_mutilingual.value,
        {
          languageInfo: (() => {
            /* 语言列表 ,当前语言位于第一个*/
            let langList = getLangList();
            return langList;
          })(),
          direction: '',
          ChangeLang: ChangeLang,
          dataChange: dataChange,
          placeholder: mappingProps.placeholder,
          title: hintPlaceholder(),
          readonly: false,
          ...props,
          defaultValue: mappingProps.defaultValue,
          isTextArea: true,
          containList: ref_mutilingual_parent.value.querySelectorAll(
            '.MultilingualText_Parent',
          ),
        },
      );
       if (ref_mutilingual_parent.value) {
           if (!mappingProps.isTextArea) {
          let domList = ref_mutilingual_parent.value.querySelectorAll('.q-field__control.relative-position.row.no-wrap')
             domList ? domList.forEach(item => item.style.height = 'auto') : ''

        } else {
          let domList = ref_mutilingual_parent.value.querySelectorAll('.q-field__control.relative-position.row.no-wrap')
          domList?domList.forEach(item=>item.style.height='32px'):''
           }
        multilingualInstance.value&&  (multilingualInstance.value.isTextArea = mappingProps.isTextArea);
       multilingualInstance.value&&  multilingualInstance.value.render();
       }
      if (mappingProps.value) {
        setValue(mappingProps.value);
      }
    });
    watch(
      () => mappingProps.readonly,
      () => {

       multilingualInstance.value&& multilingualInstance.value.setReadOnly(mappingProps.readonly);
      },
      { immediate: true },
    );
    watch(
      () => mappingProps.isTextArea,
      () => {
        if (ref_mutilingual_parent.value) {
           if (!mappingProps.isTextArea) {
          let domList = ref_mutilingual_parent.value.querySelectorAll('.q-field__control.relative-position.row.no-wrap')
          domList?domList.forEach(item=>item.style.height='auto'):''
        } else {
          let domList = ref_mutilingual_parent.value.querySelectorAll('.q-field__control.relative-position.row.no-wrap')
          domList?domList.forEach(item=>item.style.height='32px'):''
        }
        }

       multilingualInstance.value&&  (multilingualInstance.value.isTextArea = mappingProps.isTextArea);
       multilingualInstance.value&&  multilingualInstance.value.render();
      },
      { immediate: true },
    );
    watch(
      () => mappingProps.heightAuto,
      () => {
       multilingualInstance.value&& (multilingualInstance.value.heightAuto = mappingProps.heightAuto) ;
        multilingualInstance.value&& multilingualInstance.value.render();
      },
      { immediate: true },
    );
    watch(
      () => mappingProps.rows,
      () => {
       multilingualInstance.value&&  (multilingualInstance.value.rows = mappingProps.rows);
       multilingualInstance.value&&  multilingualInstance.value.render();
      },
      { immediate: true },
    );
    watch(
      () => mappingProps.resize,
      () => {
       multilingualInstance.value&&  (multilingualInstance.value.resize = mappingProps.resize);
        multilingualInstance.value&& multilingualInstance.value.render();
      },
      { immediate: true },
    );
    watch(
      () => mappingProps.placeholder,
      () => {
        multilingualInstance.value&& (multilingualInstance.value.placeholder = mappingProps.placeholder);
        multilingualInstance.value&& multilingualInstance.value.setPlaceHolder(mappingProps.placeholder);
       multilingualInstance.value&&  multilingualInstance.value.render();
      },
      { immediate: true },
    );

    return {
      ...obj,
      validate,
      response,
      ref_mutilingual_parent,
      attrs,
      // styles,
      mappingProps,
      ref_mutilingual,
      multilingualInstance,
      getLangList,
      mainRules,
      focus
    };
  },
});
</script>

<style lang="scss" scoped></style>
